//   Copyright 2012,2013 Vaughn Vernon
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package com.saasovation.common.port.adapter.notification;

import java.util.ArrayList;
import java.util.List;

import com.saasovation.common.domain.model.DomainEvent;
import com.saasovation.common.event.EventStore;
import com.saasovation.common.event.StoredEvent;
import com.saasovation.common.notification.Notification;
import com.saasovation.common.notification.NotificationPublisher;
import com.saasovation.common.notification.NotificationSerializer;
import com.saasovation.common.notification.PublishedNotificationTracker;
import com.saasovation.common.notification.PublishedNotificationTrackerStore;
import com.saasovation.common.port.adapter.messaging.rabbitmq.ConnectionSettings;
import com.saasovation.common.port.adapter.messaging.rabbitmq.Exchange;
import com.saasovation.common.port.adapter.messaging.rabbitmq.MessageParameters;
import com.saasovation.common.port.adapter.messaging.rabbitmq.MessageProducer;

/**
 * @通知发布者：RabbitMQ通知发布者
 */
public class RabbitMQNotificationPublisher implements NotificationPublisher {

    /**
     * 事件存储
     */
    private EventStore eventStore;
    /**
     * 交换名
     */
    private String exchangeName;
    /**
     * 已发布的通知跟踪存储
     */
    private PublishedNotificationTrackerStore publishedNotificationTrackerStore;

    /**
     * 由以下参数构造：RabbitMQ通知发布者
     * @param anEventStore                          事件存储
     * @param aPublishedNotificationTrackerStore    已发布的通知跟踪存储
     * @param aMessagingLocator
     */
    public RabbitMQNotificationPublisher(
            EventStore anEventStore,
            PublishedNotificationTrackerStore aPublishedNotificationTrackerStore,
            Object aMessagingLocator) {

        super();

        this.setEventStore(anEventStore);
        this.setExchangeName((String) aMessagingLocator);
        this.setPublishedNotificationTrackerStore(aPublishedNotificationTrackerStore);
    }

    /**
     * 发布通知清单
     */
    @Override
    public void publishNotifications() {
        // 建议已发布通知追踪器
        PublishedNotificationTracker publishedNotificationTracker =
                this.publishedNotificationTrackerStore().publishedNotificationTracker();
        // 列出未发布的通知
        List<Notification> notifications =
            this.listUnpublishedNotifications(
                    publishedNotificationTracker.mostRecentPublishedNotificationId());
        // 建立消息生产者
        MessageProducer messageProducer = this.messageProducer();

        try {
            // 遍历通知清单，逐一发布
            for (Notification notification : notifications) {
                this.publish(notification, messageProducer);
            }
            // 从已发布通知追踪器存储中，追踪最近已发布的通知
            this.publishedNotificationTrackerStore()
                .trackMostRecentPublishedNotification(
                    publishedNotificationTracker,
                    notifications);
        } finally {
            // 最后把消息生产者关掉
            messageProducer.close();
        }
    }

    @Override
    public boolean internalOnlyTestConfirmation() {
        throw new UnsupportedOperationException("Not supported by production implementation.");
    }

    /**
     * 获取事件存储
     * @return  返回事件存储
     */
    private EventStore eventStore() {
        return this.eventStore;
    }

    /**
     * 设置事件存储
     * @param anEventStore  事件存储
     */
    private void setEventStore(EventStore anEventStore) {
        this.eventStore = anEventStore;
    }

    /**
     * 获取交换名
     * @return  返回交换名
     */
    private String exchangeName() {
        return this.exchangeName;
    }

    /**
     * 设置交换名
     * @param anExchangeName    交换名
     */
    private void setExchangeName(String anExchangeName) {
        this.exchangeName = anExchangeName;
    }

    /**
     * 列出未发布的通知
     * @param aMostRecentPublishedMessageId         最近发布的邮件ID
     * @return
     */
    private List<Notification> listUnpublishedNotifications(
            long aMostRecentPublishedMessageId) {

        // 此后的所有已存储事件
        List<StoredEvent> storedEvents =
            this.eventStore().allStoredEventsSince(aMostRecentPublishedMessageId);
        // 从已存储事件获取通知清单
        List<Notification> notifications =
            this.notificationsFrom(storedEvents);

        return notifications;
    }

    /**
     * 获取消息生产者
     * @return  返回消息生产者
     */
    private MessageProducer messageProducer() {

        // creates my exchange if non-existing
        // 如果不存在，创建一个交换器
        Exchange exchange =
            Exchange.fanOutInstance(
                    ConnectionSettings.instance(),
                    this.exchangeName(),
                    true);

        // create a message producer used to forward events
        // 创建用于转发事件的消息生成器
        MessageProducer messageProducer = MessageProducer.instance(exchange);

        return messageProducer;
    }

    /**
     * 从（已存储事件清单）获取通知清单
     * @param aStoredEvents 已存储事件清单
     * @return      返回列表
     */
    private List<Notification> notificationsFrom(List<StoredEvent> aStoredEvents) {
        // 根据已存储事件清单初始化通知清单
        List<Notification> notifications =
            new ArrayList<Notification>(aStoredEvents.size());

        // 遍历已存储事件清单
        for (StoredEvent storedEvent : aStoredEvents) {
            // 转换已存储事件到领域事件
            DomainEvent domainEvent = storedEvent.toDomainEvent();
            // 由事件ID及领域事件，获得通知
            Notification notification =
                new Notification(storedEvent.eventId(), domainEvent);
            // 追加通知到通知清单中
            notifications.add(notification);
        }

        return notifications;
    }

    /**
     * 发布
     * @param aNotification     通知
     * @param aMessageProducer  消息生产者
     */
    private void publish(
            Notification aNotification,
            MessageProducer aMessageProducer) {
        // 获取耐用文本参数
        MessageParameters messageParameters =
            MessageParameters.durableTextParameters(
                    aNotification.typeName(),
                    Long.toString(aNotification.notificationId()),
                    aNotification.occurredOn());
        // 序列化通知
        String notification =
            NotificationSerializer
                .instance()
                .serialize(aNotification);
        // 消息生产者发布：通知及消息参数
        aMessageProducer.send(notification, messageParameters);
    }

    /**
     * 获取已发布通知追踪器存储
     * @return  返回已发布通知追踪器存储
     */
    private PublishedNotificationTrackerStore publishedNotificationTrackerStore() {
        return publishedNotificationTrackerStore;
    }

    /**
     * 设置已发布通知追踪器存储
     * @param publishedNotificationTrackerStore 已发布通知追踪器存储
     */
    private void setPublishedNotificationTrackerStore(PublishedNotificationTrackerStore publishedNotificationTrackerStore) {
        this.publishedNotificationTrackerStore = publishedNotificationTrackerStore;
    }
}
